import styles from './index.module.scss';
import { NavBar, TextArea, Toast } from 'antd-mobile';
import { useDispatch } from 'react-redux';
import {
  getCommentsByIdAction,
  getReplyCommentsByIdAction,
  sendCommentAction,
  updateReplyCommentCountAction,
} from '@/store/action/comments';
import { useEffect, useRef, useState } from 'react';
import { useAppSelector } from '@/store/reducer';
import { updateDetailsCommentsAction } from '@/store/action/article';
import { TextAreaRef } from 'antd-mobile/es/components/text-area';
type Props = {
  // 评论的作者的名字
  name?: string;
  onBack: () => void;
};
export default function CommentInput({ name, onBack }: Props) {
  const [value, setValue] = useState('');
  const dispatch = useDispatch();

  const {
    details: { art_id },
  } = useAppSelector((state) => state.article);

  const {
    comments: { total_count },
    originComment: { com_id },
  } = useAppSelector((state) => state.comments);

  const {
    replyComments: { results },
  } = useAppSelector((state) => state.comments);

  // 点击评论时,自动聚焦
  const textRef = useRef<TextAreaRef>(null);
  useEffect(() => {
    textRef.current?.focus();
  }, []);

  // console.log('total_count', total_count);
  useEffect(() => {
    // 更新文章评论个数
    dispatch(updateDetailsCommentsAction(total_count));

    // 更新回复评论数
    dispatch(updateReplyCommentCountAction(results.length));
  }, [dispatch, total_count, results]);

  // 发布评论
  const handlePublish = async () => {
    if (com_id) {
      //发表回复评论
      await dispatch(
        sendCommentAction({ content: value, target: com_id, art_id })
      );
      // 重新获取回复评论列表
      await dispatch(getReplyCommentsByIdAction({ type: 'c', source: com_id }));
      // 重新获取评论列表
      await dispatch(getCommentsByIdAction({ type: 'a', source: art_id }));
    } else {
      // 发布文章评论
      await dispatch(sendCommentAction({ content: value, target: art_id }));
      // 重新获取评论列表
      await dispatch(getCommentsByIdAction({ type: 'a', source: art_id }));
    }
    // 关闭弹窗
    onBack();
    // 提示
    Toast.show({ content: '评论成功' });
  };

  return (
    <div className={styles.root}>
      <NavBar
        right={
          <span className="publish" onClick={handlePublish}>
            发表
          </span>
        }
        onBack={onBack}
      >
        {name ? '回复评论' : '评论文章'}
      </NavBar>
      <div className="input-area">
        {/* 回复别人的评论时显示：@某某 */}
        {name && <div className="at">@{name}:</div>}

        {/* 评论内容输入框 */}
        <TextArea
          ref={textRef}
          placeholder="说点什么~"
          rows={10}
          value={value}
          onChange={(val) => setValue(val)}
        />
      </div>
    </div>
  );
}
